//
//  ILGShare.m
//  ILGPlatformSDK
//
//  Created by Happy on 6/22/16.
//  Copyright © 2016 ZhanCheng. All rights reserved.
//
#import "ILGShare.h"
#import "ILGThirdDelegate.h"
#import "ILGUtils.h"

#if __has_include(<TencentOpenAPI/TencentOAuth.h>)
#import <TencentOpenAPI/TencentOAuth.h>
#endif

static NSString * const ILGShareWBCallbackURL = @"https://api.weibo.com/oauth2/default.html"; //微博默认回调页

typedef void(^ILGBShareCallBackType)(NSError *error, NSDictionary *result);

@interface ILGShare () {
}
@property (nonatomic, copy) ILGBShareCallBackType callback;
@end


@implementation ILGShare
+ (ILGShare *)shareInstance {
    static ILGShare *share = nil;
    if (!share) {
        share = [[ILGShare alloc] init];
        
        [ILGThirdDelegate sharedInstance].shareCallback = ^(NSError *error, NSDictionary *result, ILGThirdType shareType) {
            share.callback(error, result);
        };

    }
    return share;
}

#pragma mark - Share Method
- (void)share:(ILGShareContent *)shareContent callback:(void(^)(NSError *error, NSDictionary *result))callback {
    [self share:shareContent shareType:shareContent.shareType callback:callback];
}

- (void)share:(ILGShareContent *)shareContent shareType:(NSInteger)shareType callback:(void(^)(NSError *error, NSDictionary *result))callback {
    _callback = callback;
    
    if (shareType == ILGThirdTypeWeiXin) {
#ifdef ILGWXSDKIncluded
        if (![WXApi isWXAppInstalled]) {
            NSError *noInstallError = [NSError errorWithDomain:@"com.zbsdk.login" code:-2 userInfo:@{NSLocalizedDescriptionKey:@"您还没有安装微信客户端"}];
            callback(noInstallError, nil);
            return;
        }
        if ([ILGThirdDelegate sharedInstance].wxAppId.length == 0) {
            NSError *weiXinError = [NSError errorWithDomain:@"com.zbsdk.login" code:-1 userInfo:@{NSLocalizedDescriptionKey:@"缺少参数微信appid"}];
            callback(weiXinError, nil);
            return;
        }
        
        [self shareInWeiXin:shareContent];
#else
        NSLog(@"ILGSDK 微信分享暂未开放");
#endif
        
    } else if (shareType == ILGThirdTypeFacebook) {
#ifdef ILGFacebookSDKIncluded
        [self shareInFacebook:shareContent];
#else
        NSLog(@"ILGSDK Facebook分享暂未开放");
#endif
    } else if (shareType == ILGThirdTypeQQ) {
        
    } else if (shareType == ILGThirdTypeWeiBo) {
        
    }
}


#pragma mark - 微信分享
#ifdef ILGWXSDKIncluded
- (void)shareInWeiXin:(ILGShareContent *)shareContent {
    switch (shareContent.contentType) {
        case ILGShareContentTypeText:
            [self weixinShareText:shareContent];
            break;
            
        case ILGShareContentTypeImage:
            [self weixinShareImage:shareContent];
            break;
            
        case ILGShareContentTypeLink:
            [self weixinShareLink:shareContent];
            break;
            
        case ILGShareContentTypeVideo:
            [self weixinShareVideo:shareContent];
            break;
    }
}
- (void)weixinShareText:(ILGShareContent *)shareContent {
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.text = shareContent.contentText;
    req.bText = YES;
    req.scene = shareContent.scene;
    [WXApi sendReq:req];
}
- (void)weixinShareImage:(ILGShareContent *)shareContent {
    NSURL *imageURL = nil;
    
    if ([shareContent.imageURL hasPrefix:@"http"]) {
        imageURL = [NSURL URLWithString:shareContent.imageURL];
    } else {
        imageURL = [NSURL fileURLWithPath:shareContent.imageURL];
    }
    
    /*
     Photos must be less than 12MB in size
     People need the native Facebook for iOS app installed, version 7.0 or higher
     */
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];
    if (!image) {
        NSError *error = [NSError errorWithDomain:@"com.zcbsdk.share" code:-3 userInfo:@{NSLocalizedDescriptionKey:@"读取图片失败"}];
        _callback(error, nil);
        return;
    }
    
    WXMediaMessage *message = [WXMediaMessage message];
    
    NSURL *thumbImageUrl = nil;
    if (shareContent.thumbImageURL) { //设置缩略图
        if ([shareContent.thumbImageURL hasPrefix:@"http"]) {
            thumbImageUrl = [NSURL URLWithString:shareContent.thumbImageURL];
        } else {
            thumbImageUrl = [NSURL fileURLWithPath:shareContent.thumbImageURL];
        }
        
    } else {
        thumbImageUrl = imageURL;
        
    }
    UIImage *thumbImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:thumbImageUrl]];
    NSData *thumbDataCompressed = [ILGUtils imageCompress:thumbImage targetWidth:160 compression:1.0];
    [message setThumbImage:[UIImage imageWithData:thumbDataCompressed]];
    
    
    if (shareContent.contentTitle) {
        message.title = shareContent.contentTitle;
    }
    if (shareContent.contentDescription) {
        message.description = shareContent.contentTitle;
    }
    
    WXImageObject *imageObject = [WXImageObject object];
    imageObject.imageData = UIImagePNGRepresentation(image);
    message.mediaObject = imageObject;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = shareContent.scene;
    [WXApi sendReq:req];
}
// 微信可以显示Title和缩略图
- (void)weixinShareLink:(ILGShareContent *)shareContent {
    WXMediaMessage *message = [WXMediaMessage message];
    if (shareContent.contentTitle) {
        message.title = shareContent.contentTitle;
    }
    if (shareContent.contentDescription) {
        message.description = shareContent.contentDescription;
    }
    
    [message setThumbImage:[UIImage imageWithData:[self shareThumbImage:shareContent.thumbImageURL]]];
    
    WXWebpageObject *webpageObject = [WXWebpageObject object];
    webpageObject.webpageUrl = shareContent.contentURL;
    message.mediaObject = webpageObject;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = shareContent.scene;
    
    [WXApi sendReq:req];
}
- (void)weixinShareVideo:(ILGShareContent *)shareContent {
    NSLog(@"ILGBSDK error:微信分享视频暂未实现");
}
#endif


#pragma mark - QQ
#ifdef ILGQQSDKIncluded
- (void)qqShare:(ILGShareContent *)shareContent {
    QQApiNewsObject* img = [QQApiNewsObject objectWithURL:[NSURL URLWithString:shareContent.contentURL]
                                                    title:shareContent.contentTitle
                                              description:shareContent.contentDescription
                                         previewImageData:[self shareThumbImage:shareContent.thumbImageURL]];
    SendMessageToQQReq* req = [SendMessageToQQReq reqWithContent:img];
    
    [QQApiInterface sendReq:req];
}
#endif


#pragma mark - 微博
#ifdef ILGWBSDKIncluded
- (void)weiBoShareLink:(ILGShareContent *)shareContent {
    WBMessageObject *message = [WBMessageObject message];
    
    //分享多媒体文件
    WBWebpageObject *webpage = [WBWebpageObject object];
    NSTimeInterval time = [[NSDate date] timeIntervalSinceNow] + 756;
    NSString *objectID = [NSString stringWithFormat:@"%lf",time];
    webpage.objectID = objectID;
    webpage.title = shareContent.contentTitle;
    webpage.description = shareContent.contentDescription;
    webpage.thumbnailData = [self shareThumbImage:shareContent.thumbImageURL];
    webpage.webpageUrl = shareContent.contentURL;
    message.mediaObject = webpage;
    
    WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
    authRequest.redirectURI = IWHWeiBoRedirectURL;
    authRequest.scope = @"all";
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:message authInfo:authRequest access_token:nil];
    request.userInfo = @{};
    request.shouldOpenWeiboAppInstallPageIfNotInstalled = NO;
    [WeiboSDK sendRequest:request];
}
#endif

#pragma mark - Facebook分享
#ifdef ILGFacebookSDKIncluded
- (void)shareInFacebook:(ILGShareContent *)shareContent {
    switch (shareContent.contentType) {
        case ILGShareContentTypeText:
            [self facebookShareText:shareContent];
            break;
        case ILGShareContentTypeImage:
            [self facebookShareImage:shareContent];
            break;
        case ILGShareContentTypeLink:
            [self facebookShareLink:shareContent];
            break;
        case ILGShareContentTypeVideo:
            [self facebookShareVideo:shareContent];
            break;
    }
}

- (void)facebookShareText:(ILGShareContent *)shareContent {
    NSLog(@"ILGBSDK Error: facebook不能分享纯文本");
}

- (void)facebookShareImage:(ILGShareContent *)shareContent {
    NSURL *imageURL = nil;
    
    if ([shareContent.imageURL hasPrefix:@"http"]) {
        imageURL = [NSURL URLWithString:shareContent.imageURL];
    } else {
        imageURL = [NSURL fileURLWithPath:shareContent.imageURL];
    }
    
    /*
     Photos must be less than 12MB in size
     People need the native Facebook for iOS app installed, version 7.0 or higher
     */
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];
    if (!image) {
        NSError *error = [NSError errorWithDomain:@"com.zcbsdk.share" code:-3 userInfo:@{NSLocalizedDescriptionKey:@"读取图片失败"}];
        _shareCallback(error, nil);
        return;
    }
    
    FBSDKSharePhoto *photo = [[FBSDKSharePhoto alloc] init];
    photo.image = image;
    photo.userGenerated = YES;
    FBSDKSharePhotoContent *content = [[FBSDKSharePhotoContent alloc] init];
    content.photos = @[photo];
    
    [FBSDKShareDialog showFromViewController:[self currentViewController] withContent:content delegate:[ILGThirdDelegate sharedInstance]];
}

- (void)facebookShareVideo:(ILGShareContent *)shareContent {
    FBSDKShareVideo *video = [[FBSDKShareVideo alloc] init];
    video.videoURL = [NSURL URLWithString:shareContent.videoURL];
    FBSDKShareVideoContent *content = [[FBSDKShareVideoContent alloc] init];
    content.video = video;
    
    [FBSDKShareDialog showFromViewController:nil withContent:content delegate:[ILGThirdDelegate sharedInstance]];
}

//Facebook可以显示缩略图、Title和描述
- (void)facebookShareLink:(ILGShareContent *)shareContent {
    FBSDKShareLinkContent *content = [[FBSDKShareLinkContent alloc] init];
    content.contentURL = [NSURL URLWithString:shareContent.contentURL];
    
    if (shareContent.thumbImageURL) { //Facebook分享缩略图只能是网络地址
        content.imageURL = [NSURL URLWithString:shareContent.thumbImageURL];
    }
    if (shareContent.contentTitle) {
        content.contentTitle = shareContent.contentTitle;
    }
    if (shareContent.contentDescription) {
        content.contentDescription = shareContent.contentDescription;
    }
    
    //这种方式无法显示缩略图，只能使用下面方法
    //      [FBSDKShareDialog showFromViewController:[self currentViewController] withContent:content delegate:self];
    
    FBSDKShareDialog *dialog = [[FBSDKShareDialog alloc] init];
    dialog.fromViewController = nil;
    dialog.mode = FBSDKShareDialogModeFeedWeb;
    dialog.shareContent = content;
    dialog.delegate = [ILGThirdDelegate sharedInstance];
    [dialog show];
}
#endif


#pragma mark - Other
- (NSData *)shareThumbImage:(NSString *)thumbImageUrl {
    NSData *imageData = nil;
    if (thumbImageUrl.length > 0) {
        NSURL *thumbImageURL = nil;
        if ([thumbImageUrl hasPrefix:@"http"]) {
            thumbImageURL = [NSURL URLWithString:thumbImageUrl];
        } else {
            thumbImageURL = [NSURL fileURLWithPath:thumbImageUrl];
        }
        imageData = [NSData dataWithContentsOfURL:thumbImageURL];
        
    } else {
        UIImage *image = [UIImage imageNamed:@"AppIcon20x20"];
        imageData =  UIImageJPEGRepresentation(image, 1.0);
    }
    if (imageData.length > 30000) {
        imageData = [[UIImage imageWithData:imageData] ilg_imageCompress:50 compression:0.5];
    }
    return imageData;
}

- (UIViewController *)currentViewController {
    UIViewController *currentVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    while (currentVC.presentedViewController) {
        currentVC = currentVC.presentedViewController;
    }
    
    return currentVC;
}
@end
